package com.cater.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.MediaPrintableArea;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.cater.sys.entity.Filestorage;
import com.cater.sys.service.FilestorageService;
import com.google.common.io.Files;

public class UploadUtil {
	/**
	 * @param file
	 *            //文件对象
	 * @param filePath
	 *            //上传路径
	 * @param fileName
	 *            //文件名
	 * @return 文件名
	 */
	public static String fileUp(MultipartFile file, String filePath, String fileName) {
		String dataPath = "/static/upload/";
		String extName = ""; // 扩展名格式：
		try {
			if (file.getOriginalFilename().lastIndexOf(".") >= 0) {
				extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			}
			copyFile(file.getInputStream(), filePath, fileName + extName).replaceAll("-", "");
		} catch (IOException e) {
			// System.out.println(e);
		}
		return dataPath + fileName + extName;
	}
	public static String fileMultiUp(MultipartFile file, String filePath, String fileName) {
		String dataPath = "/static/upload/";
		String extName = ""; // 扩展名格式：
		try {
			if (file.getOriginalFilename().lastIndexOf(".") >= 0) {
				extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			}
			copyFile(file.getInputStream(), filePath, fileName + extName).replaceAll("-", "");
		} catch (IOException e) {
			// System.out.println(e);
		}
		return dataPath + fileName + extName;
	}
	public static boolean fileUpload(@RequestParam MultipartFile[] file_Up, String realPath, String filName,
			HttpServletRequest request) {
		if (file_Up != null) {
			if (realPath == null || realPath == "") {
				realPath = request.getSession().getServletContext().getRealPath("/");
			} else {
				realPath = request.getSession().getServletContext().getRealPath("/") + realPath;
			}
			for (MultipartFile files : file_Up) {
				if (filName == null) {
					// 表示用files里已有名字
					filName = files.getOriginalFilename();
				}
				try {
					byte[] bytes = files.getBytes();
					File fil = new File(realPath);
					// 如果文件夹不存在则创建
					if (!fil.exists() && !fil.isDirectory()) {
						System.out.println("文件夹不存在，自动创建");
						fil.mkdirs();
					}
					/*File dir = new File(realPath);
					if (dir.exists()) {
						dir.delete();
						System.out.println("删除文件成功");
						
						 * boolean b = dir.mkdirs(); if (!b) return false;
						 
					}else {
						System.out.println("删除文件失败");
					}*/
					files.transferTo(new File(realPath + filName));
					File f = new File(realPath + filName);
					Files.write(bytes, f);
				} catch (IOException e) {
					System.out.println((realPath + filName)+"上传错误！"+e.getMessage());
					return false;
				}
			}
		}
		return true;
	}

	public static void fileUploads(MultipartFile[] file_Up, MultipartFile files, Integer id, String attributetype,
			HttpServletRequest request, FilestorageService services) {
		SimpleDateFormat formatter = new SimpleDateFormat("HHmmssms");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
		SimpleDateFormat sdfm = new SimpleDateFormat("MM");
		SimpleDateFormat sdfd = new SimpleDateFormat("dd");
		String realPath = request.getSession().getServletContext().getRealPath("/") + "static/upload/"
				+ sdf.format(new Date()) + "/";
		File file = new File(realPath);
		// 如果文件夹不存在则创建
		if (!file.exists() && !file.isDirectory()) {
			System.out.println("//不存在年份");
			file.mkdir();
		}
		File filen = new File(realPath + sdfm.format(new Date()) + "/");
		// 如果文件夹不存在则创建
		if (!filen.exists() && !filen.isDirectory()) {
			System.out.println("//不存在月份");
			filen.mkdir();
		}
		File filed = new File(realPath + sdfm.format(new Date()) + "/" + sdfd.format(new Date()) + "/");
		String realPaths = realPath + sdfm.format(new Date()) + "/" + sdfd.format(new Date()) + "/";
		// 如果文件夹不存在则创建
		if (!filed.exists() && !filed.isDirectory()) {
			System.out.println("//不存在日");
			filed.mkdir();
		}
		List<Filestorage> list = new ArrayList<Filestorage>();
		if (file_Up != null) {
			int ns = 0;
			for (MultipartFile multipartFile : file_Up) {
				Filestorage storage = new Filestorage();
				try {
					String flieType = multipartFile.getOriginalFilename()
							.substring(multipartFile.getOriginalFilename().lastIndexOf("."));
					byte[] bytes = multipartFile.getBytes();
					File dir = new File(realPaths);
					String filName = formatter.format(new Date()) + (int) (Math.random() * 100) + ns + flieType;
					multipartFile.transferTo(new File(realPaths + filName));
					if (!dir.exists()) {
						dir.mkdirs();
						/* if (!b) return null; */
					}
					File f = new File(realPaths + filName);
					Files.write(bytes, f);
					storage.setFlieName(sdf.format(new Date()) + "/" + sdfm.format(new Date()) + "/"
							+ sdfd.format(new Date()) + "/" + filName);
					storage.setFlieType(flieType);
					storage.setAttributeId(id.toString());
					storage.setAttributetype(attributetype.toString());
					Double ss = (double) (multipartFile.getSize() / 1024);
					storage.setFlieSize(ss);
					if (flieType.equalsIgnoreCase(".jpg") || flieType.equalsIgnoreCase(".bmp")
							|| flieType.equalsIgnoreCase(".gif") || flieType.equalsIgnoreCase(".psd")
							|| flieType.equalsIgnoreCase(".png") || flieType.equalsIgnoreCase(".pcx")
							|| flieType.equalsIgnoreCase(".dxf") || flieType.equalsIgnoreCase(".cdr")
							|| flieType.equalsIgnoreCase(".eps")) {
						storage.setType(1);
					} else if (flieType.equalsIgnoreCase(".AVI") || flieType.equalsIgnoreCase(".wma")
							|| flieType.equalsIgnoreCase(".rmvb") || flieType.equalsIgnoreCase(".rm")
							|| flieType.equalsIgnoreCase(".flash") || flieType.equalsIgnoreCase(".mp4")
							|| flieType.equalsIgnoreCase(".mid") || flieType.equalsIgnoreCase(".3GP")
							|| flieType.equalsIgnoreCase(".ogg")) {
						storage.setType(2);
					} else {
						storage.setType(3);
					}
					list.add(storage);
				} catch (IOException e) {
					System.out.println(e);

				}
				ns++;
			}
			/* return list; */
		}
		for (Filestorage filestorage : list) {
			services.save(filestorage);
		}
		// 单文件
		if (files != null) {
			Filestorage storage = new Filestorage();
			try {
				String flieType = files.getOriginalFilename().substring(files.getOriginalFilename().lastIndexOf("."));
				byte[] bytes = files.getBytes();
				File dir = new File(realPaths);
				String filName = formatter.format(new Date()) + (int) (Math.random() * 100) + flieType;
				files.transferTo(new File(realPaths + filName));
				if (!dir.exists()) {
					dir.mkdirs();
					/* if (!b) return null; */
				}
				File f = new File(realPaths + filName);
				Files.write(bytes, f);
				storage.setFlieName(sdf.format(new Date()) + "/" + sdfm.format(new Date()) + "/"
						+ sdfd.format(new Date()) + "/" + filName);
				storage.setFlieType(flieType);
				storage.setAttributeId(id.toString());
				storage.setAttributetype(attributetype);
				Double ss = (double) (files.getSize() / 1024);
				storage.setFlieSize(ss);
				if (flieType.equalsIgnoreCase(".jpg") || flieType.equalsIgnoreCase(".bmp")
						|| flieType.equalsIgnoreCase(".gif") || flieType.equalsIgnoreCase(".psd")
						|| flieType.equalsIgnoreCase(".png") || flieType.equalsIgnoreCase(".pcx")
						|| flieType.equalsIgnoreCase(".dxf") || flieType.equalsIgnoreCase(".cdr")
						|| flieType.equalsIgnoreCase(".eps")) {
					storage.setType(1);
				} else if (flieType.equalsIgnoreCase(".AVI") || flieType.equalsIgnoreCase(".wma")
						|| flieType.equalsIgnoreCase(".rmvb") || flieType.equalsIgnoreCase(".rm")
						|| flieType.equalsIgnoreCase(".flash") || flieType.equalsIgnoreCase(".mp4")
						|| flieType.equalsIgnoreCase(".mid") || flieType.equalsIgnoreCase(".3GP")
						|| flieType.equalsIgnoreCase(".ogg")) {
					storage.setType(2);
				} else {
					storage.setType(3);
				}
				list.add(storage);
			} catch (IOException e) {
				/* return null; */
				System.out.println(e);
			}
			for (Filestorage filestorage : list) {
				services.save(filestorage);
			}
		}
	}

	public static void fileUploads(MultipartFile[] file_Up, MultipartFile files, String id, String attributetype,
			Integer type, HttpServletRequest request, FilestorageService services) {
		SimpleDateFormat formatter = new SimpleDateFormat("HHmmssms");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
		SimpleDateFormat sdfm = new SimpleDateFormat("MM");
		SimpleDateFormat sdfd = new SimpleDateFormat("dd");
		String realPath = request.getSession().getServletContext().getRealPath("/") + "static/upload/"
				+ sdf.format(new Date()) + "/";
		System.out.println(realPath);
		File file = new File(realPath);
		// 如果文件夹不存在则创建
		if (!file.exists() && !file.isDirectory()) {
			System.out.println("//不存在年份");
			file.mkdir();
		}
		File filen = new File(realPath + sdfm.format(new Date()) + "/");
		// 如果文件夹不存在则创建
		if (!filen.exists() && !filen.isDirectory()) {
			System.out.println("//不存在月份");
			filen.mkdir();
		}
		File filed = new File(realPath + sdfm.format(new Date()) + "/" + sdfd.format(new Date()) + "/");
		String realPaths = realPath + sdfm.format(new Date()) + "/" + sdfd.format(new Date()) + "/";
		// 如果文件夹不存在则创建
		if (!filed.exists() && !filed.isDirectory()) {
			System.out.println("//不存在日");
			filed.mkdir();
		}
		List<Filestorage> list = new ArrayList<Filestorage>();
		if (file_Up != null) {
			int ns = 0;
			for (MultipartFile multipartFile : file_Up) {
				Filestorage storage = new Filestorage();
				try {
					String flieType = multipartFile.getOriginalFilename()
							.substring(multipartFile.getOriginalFilename().lastIndexOf("."));
					byte[] bytes = multipartFile.getBytes();
					File dir = new File(realPaths);
					String filName = formatter.format(new Date()) + (int) (Math.random() * 100) + ns + flieType;
					multipartFile.transferTo(new File(realPaths + filName));
					if (!dir.exists()) {
						dir.mkdirs();
						/* if (!b) return null; */
					}
					File f = new File(realPaths + filName);
					Files.write(bytes, f);
					storage.setFlieName(sdf.format(new Date()) + "/" + sdfm.format(new Date()) + "/"
							+ sdfd.format(new Date()) + "/" + filName);
					storage.setFlieType(flieType);
					storage.setAttributeId(id.toString());
					storage.setAttributetype(attributetype);
					Double ss = (double) (multipartFile.getSize() / 1024);
					storage.setFlieSize(ss);
					if ("2".equals(attributetype) || flieType.equalsIgnoreCase(".jpg")
							|| flieType.equalsIgnoreCase(".bmp") || flieType.equalsIgnoreCase(".gif")
							|| flieType.equalsIgnoreCase(".psd") || flieType.equalsIgnoreCase(".png")
							|| flieType.equalsIgnoreCase(".pcx") || flieType.equalsIgnoreCase(".dxf")
							|| flieType.equalsIgnoreCase(".cdr") || flieType.equalsIgnoreCase(".eps")) {
						PictureCompressionUtil.reduceImg(realPaths + filName, realPaths + filName, 480, 480, 0f);
					}
					storage.setType(type);
					list.add(storage);
				} catch (IOException e) {
					System.out.println(e);

				}
				ns++;
			}
			/* return list; */
		}
		for (Filestorage filestorage : list) {
			services.save(filestorage);
		}
		// 单文件
		if (files != null) {
			Filestorage storage = new Filestorage();
			try {
				String flieType = files.getOriginalFilename().substring(files.getOriginalFilename().lastIndexOf("."));
				byte[] bytes = files.getBytes();
				File dir = new File(realPaths);
				String filName = formatter.format(new Date()) + (int) (Math.random() * 100) + flieType;
				files.transferTo(new File(realPaths + filName));
				if (!dir.exists()) {
					dir.mkdirs();
					/* if (!b) return null; */
				}
				File f = new File(realPaths + filName);
				Files.write(bytes, f);
				storage.setFlieName(sdf.format(new Date()) + "/" + sdfm.format(new Date()) + "/"
						+ sdfd.format(new Date()) + "/" + filName);
				storage.setFlieType(flieType);
				storage.setAttributeId(id.toString());
				storage.setAttributetype(attributetype);
				Double ss = (double) (files.getSize() / 1024);
				if ("2".equals(attributetype) || flieType.equalsIgnoreCase(".jpg") || flieType.equalsIgnoreCase(".bmp")
						|| flieType.equalsIgnoreCase(".gif") || flieType.equalsIgnoreCase(".psd")
						|| flieType.equalsIgnoreCase(".png") || flieType.equalsIgnoreCase(".pcx")
						|| flieType.equalsIgnoreCase(".dxf") || flieType.equalsIgnoreCase(".cdr")
						|| flieType.equalsIgnoreCase(".eps")) {
					PictureCompressionUtil.reduceImg(realPaths + filName, realPaths + filName, 480, 480, 0f);
				}
				storage.setFlieSize(ss);
				storage.setType(type);
				list.add(storage);
			} catch (IOException e) {
				/* return null; */
				System.out.println(e);
			}
			for (Filestorage filestorage : list) {
				services.save(filestorage);
			}
		}
	}

	public static void fileUploadsf(MultipartFile[] file_Up, MultipartFile files, String id, String attributetype,
			HttpServletRequest request, FilestorageService services) {
		SimpleDateFormat formatter = new SimpleDateFormat("HHmmssms");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
		SimpleDateFormat sdfm = new SimpleDateFormat("MM");
		SimpleDateFormat sdfd = new SimpleDateFormat("dd");
		String realPath = request.getSession().getServletContext().getRealPath("/") + "static/upload/"
				+ sdf.format(new Date()) + "/";
		File file = new File(realPath);
		// 如果文件夹不存在则创建
		if (!file.exists() && !file.isDirectory()) {
			System.out.println("//不存在年份");
			file.mkdir();
		}
		File filen = new File(realPath + sdfm.format(new Date()) + "/");
		// 如果文件夹不存在则创建
		if (!filen.exists() && !filen.isDirectory()) {
			System.out.println("//不存在月份");
			filen.mkdir();
		}
		File filed = new File(realPath + sdfm.format(new Date()) + "/" + sdfd.format(new Date()) + "/");
		String realPaths = realPath + sdfm.format(new Date()) + "/" + sdfd.format(new Date()) + "/";
		// 如果文件夹不存在则创建
		if (!filed.exists() && !filed.isDirectory()) {
			System.out.println("//不存在日");
			filed.mkdir();
		}
		List<Filestorage> list = new ArrayList<Filestorage>();
		if (file_Up != null) {
			int ns = 0;
			for (MultipartFile multipartFile : file_Up) {
				Filestorage storage = new Filestorage();
				try {
					String flieType = multipartFile.getOriginalFilename()
							.substring(multipartFile.getOriginalFilename().lastIndexOf("."));
					byte[] bytes = multipartFile.getBytes();
					File dir = new File(realPaths);
					String filName = formatter.format(new Date()) + (int) (Math.random() * 100) + ns + flieType;
					multipartFile.transferTo(new File(realPaths + filName));
					if (!dir.exists()) {
						dir.mkdirs();
						/* if (!b) return null; */
					}
					File f = new File(realPaths + filName);
					Files.write(bytes, f);
					storage.setFlieName(sdf.format(new Date()) + "/" + sdfm.format(new Date()) + "/"
							+ sdfd.format(new Date()) + "/" + filName);
					storage.setFlieType(flieType);
					storage.setAttributeId(id.toString());
					storage.setAttributetype(attributetype);
					Double ss = (double) (multipartFile.getSize() / 1024);
					storage.setFlieSize(ss);
					storage.setType(4);
					list.add(storage);
				} catch (IOException e) {
					System.out.println(e);

				}
				ns++;
			}
			/* return list; */
		}
		for (Filestorage filestorage : list) {
			services.save(filestorage);
		}
		// 单文件
		if (files != null) {
			Filestorage storage = new Filestorage();
			try {
				String flieType = files.getOriginalFilename().substring(files.getOriginalFilename().lastIndexOf("."));
				byte[] bytes = files.getBytes();
				File dir = new File(realPaths);
				String filName = formatter.format(new Date()) + (int) (Math.random() * 100) + flieType;
				files.transferTo(new File(realPaths + filName));
				if (!dir.exists()) {
					dir.mkdirs();
					/* if (!b) return null; */
				}
				File f = new File(realPaths + filName);
				Files.write(bytes, f);
				storage.setFlieName(sdf.format(new Date()) + "/" + sdfm.format(new Date()) + "/"
						+ sdfd.format(new Date()) + "/" + filName);
				storage.setFlieType(flieType);
				storage.setAttributeId(id.toString());
				storage.setAttributetype(attributetype);
				Double ss = (double) (files.getSize() / 1024);
				storage.setFlieSize(ss);
				storage.setType(4);
				list.add(storage);
			} catch (IOException e) {
				/* return null; */
				System.out.println(e);
			}
			for (Filestorage filestorage : list) {
				List<Filestorage> filestor = services.getAllByattributeId(id, "14");
				int ss = 0;
				if (filestor != null) {
					for (Filestorage filestorage2 : filestor) {
						if (filestorage2.getType() == 4) {
							File fil = new File(realPath + filestorage2.getFlieName());
							if (fil.exists()) {
								fil.delete();
							}
							filestorage2.setFlieName(filestorage.getFlieName());
							services.update(filestorage2);
							ss = 1;
						}
					}
				}
				if (ss == 0) {
					services.save(filestorage);
				}
			}
		}
	}

	public static void prints(String fileName, HttpServletRequest request) throws PrintException, IOException {
		String realPath = request.getSession().getServletContext().getRealPath("/") + "static/upload/";
		// 构建打印请求属性集
		PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
		// 设置打印格式，因为未确定类型，所以选择autosense
		DocFlavor flavor = DocFlavor.INPUT_STREAM.JPEG;
		// 查找所有的可用的打印服务
		PrintService[] printService = PrintServiceLookup.lookupPrintServices(flavor, pras);
		// 如果没有获取打印机
		if (printService.length == 0) {
			// 终止程序
			return;
		}
		// 定位默认的打印服务
		PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
		// 获得打印工作
		DocPrintJob job = defaultService.createPrintJob();
		DocAttributeSet das = new HashDocAttributeSet();
		das.add(new MediaPrintableArea(0, 0, 2, (float) 1.1, MediaPrintableArea.INCH));
		// 设置打印内容
		FileInputStream fin = new FileInputStream(realPath + fileName);
		Doc doc = new SimpleDoc(fin, flavor, das);
		// 出现设置对话框
		// PrintService service = ServiceUI.printDialog(null, 200,
		// 00,printService, defaultService, flavor, pras);
		// if (service != null) {
		// 开始打印
		job.print(doc, pras);
		fin.close();
	}

	/*
	 * public static void main(String[] args) { // 遍历文件 File mFile = new
	 * File("d:/text/"); if (mFile.exists() && mFile.isDirectory()) { List<File>
	 * mlist = new ArrayList<File>(); getAllFile(mFile, mlist); // 已经获取了所有图片 for
	 * (File file2 : mlist) { Long log = file2.lastModified(); Calendar cd =
	 * Calendar.getInstance(); cd.setTimeInMillis(log); SimpleDateFormat
	 * dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date =
	 * cd.getTime(); String filss = file2.getAbsolutePath(); String[] s
	 * =filss.split("\\\\"); String vls = ""; for (String string : s) { vls+=string
	 * +"--------"; } System.out.println(vls+dateFormater.format(date)); } } }
	 */

	private static void getAllFile(File mFile, List<File> mlist) {
		// 1.获取子目录
		File[] files = mFile.listFiles();
		// 2.判断files是否是空的 否则程序崩溃
		if (files != null) {
			for (File file : files) {
				if (file.isDirectory()) {
					getAllFile(file, mlist);// 调用递归的方式
				} else {
					// 4. 添加到集合中去
					String fileName = file.getName();
					if (fileName.endsWith(".jpg") || fileName.endsWith(".png") || fileName.endsWith(".gif")) {
						mlist.add(file);// 如果是这几种图片格式就添加进去
					}
				}
			}
		}
	}

	/**
	 * 写文件到当前目录的upload目录中
	 * 
	 * @param in
	 * @throws IOException
	 */
	private static String copyFile(InputStream in, String dir, String realName) throws IOException {
		File file = new File(dir, realName);
		if (!file.exists()) {
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			file.createNewFile();
		}
		FileUtils.copyInputStreamToFile(in, file);
		return realName;
	}
	/**
     * @param resp
     * @param name         文件真实名字
     * @param downloadName 文件下载时名字
     */
    public static void download(HttpServletResponse resp,HttpServletRequest request, String name, String downloadName) {
        String fileName = null;
        try {
            fileName = new String(downloadName.getBytes("GBK"), "ISO-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String realPath = request.getSession().getServletContext().getContextPath();
        String path = realPath + name;
        File file = new File(path);
        resp.reset();
        resp.setContentType("application/octet-stream");
        resp.setCharacterEncoding("utf-8");
        resp.setContentLength((int) file.length());
        resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = resp.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(file));
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
